package org.yi.web.post;

import java.util.List;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yi.core.annotation.Action;
import org.yi.core.common.Constants;
import org.yi.core.enums.BlockTargetEnum;
import org.yi.core.enums.PostTypeEnum;
import org.yi.core.utils.CookieUtils;
import org.yi.core.utils.ParamUtils;
import org.yi.web.base.BaseController;
import org.yi.web.category.entity.CategoryEntity;
import org.yi.web.favorite.FavoriteEntity;
import org.yi.web.post.entity.PostEntity;

import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.ehcache.CacheKit;
import com.jfinal.plugin.ehcache.IDataLoader;

@Action(action = "article")
public class ArticleController extends BaseController {
	
	private static final Logger logger = LoggerFactory.getLogger(ArticleController.class);
	
	public void index() {
		list();
	}
	
	public void list() {
		try {
			setHeader();
			
			Map<String,String> params = ParamUtils.translateMap(getParaMap());
			// 首先获取ID， 如果没有获取到则获取拼音
			String cid = getPara("cid");
			if(StringUtils.isBlank(cid)) {
				// CID没有传入参数的时候， 获取alias参数， 并将其转换为CID
				String alias = getPara("alias");
				if("all".equalsIgnoreCase(alias)) {
					cid = "0";
				} else {
					CategoryEntity cat = CategoryEntity.dao.getByAlias(alias);
					cid = cat==null ? "0" : String.valueOf(cat.get("id"));
					setAttr("cid", cid);
				}
			}
			
			params.put("category", cid);
			params.put("type", PostTypeEnum.ARTICLE.getCode());
			Page<PostEntity> page = CacheKit.get(Constants.CACHE_KEY_SHORT, "list-"+cid+"-"+PostTypeEnum.ARTICLE.getCode()+"-"+getPara("pageNumber"));
			if(page == null) {
				page = PostEntity.dao.getPager(getPager(), params);
			}
			setAttr("page", page);
			
			loadBlocks(BlockTargetEnum.LIST);
			
			setAttr("recentReply", getRecentReply());
			
			keepPara();
			
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		render("/themes/" + getSite().get("theme") + "/list.html");
	}
	
	public void show() {
		final String id = getPara("id");
		try {
			setHeader();
			PostEntity p = PostEntity.dao.findById(id);
			setAttr("post", p);
			
			if(getFrontUser() != null) {
				FavoriteEntity findByUidAid = CacheKit.get(Constants.CACHE_KEY_MID, 
						"user"+getFrontUser().get("id")+"_article"+id+"_Favorite", new IDataLoader() {
					@Override
					public Object load() {
						return FavoriteEntity.dao.findByUidAid(getFrontUser().get("id"), id);
					}
				});
				setAttr("hasFavorite", findByUidAid == null ? false : true);
			}
			// get last and next article
			PostEntity last = PostEntity.dao.getLast(p);
			PostEntity next = PostEntity.dao.getNext(p);
			setAttr("last", last);
			setAttr("next", next);
			
			List<PostEntity> nextList = PostEntity.dao.getNext(p, Constants.DEFAULT_PAGESIZE);
			// if nextList.size not enough, get PostEntity from the start
			if(nextList.size() < Constants.DEFAULT_PAGESIZE) {
				nextList.addAll(PostEntity.dao.getNext(null, Constants.DEFAULT_PAGESIZE-nextList.size()));
			}
			setAttr("nextList", nextList);
			
			loadBlocks(BlockTargetEnum.ARTICLE);
			
			// 查询cookie中是否存在阅读痕迹， 如果存在则不增加阅读量， 否则增加阅读量
			String cookieName = getRequest().getServerName()+"-article-read-" + id;
			String readCookie = CookieUtils.getCookie(getRequest(), cookieName);
			if(readCookie == null) {
				PostEntity.dao.updateReadNum(p);
				CookieUtils.addCookie(cookieName, DigestUtils.md5Hex(id), getRequest().getServerName(), 
						Constants.config.getInt("cookie.period", 3600), getResponse());
			}
			/*// get reply num from duoshuo
			String requestURL = Constants.config.getString("duoshuo.baseurl") 
						+ "/threads/counts.json?short_name="+ Constants.config.getString("duoshuo.short_name") 
						+"&threads=" + id;
			String replyNumJson = new HttpClient().get(requestURL);
			JSONObject duoshuoResult = JSONObject.parseObject(replyNumJson);
			Object replyNum = duoshuoResult.getJSONObject("response").getJSONObject(id).get("comments");
			setAttr("reply_num", replyNum);*/
			setAttr("recentReply", getRecentReply());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		render("/themes/"+getSite().get("theme")+"/show.html");
	}

}
